/**
 * 
 *	起迪科技
 * Copyright (c) 2014-2018 QiDi,Inc.All Rights Reserved.
 */
package cn.qidisoft.edu.hzjt.controller.directory;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.model.Directory;
import cn.qidisoft.edu.hzjt.model.Employee;
import cn.qidisoft.edu.hzjt.model.Project;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.service.ICommonService;
import cn.qidisoft.edu.hzjt.service.IDirectoryService;
import cn.qidisoft.edu.hzjt.service.IProjectService;
import cn.qidisoft.edu.hzjt.utils.LogType;

/**
 * 
 * @author hhl
 * @version $Id: ProjectController.java, v 0.1 2018年10月23日 下午4:56:53 hhl Exp $
 */
@Controller
@RequestMapping(value = "directory")
public class DirectoryController {
    protected static final LoggerAdapter LOGGER = LoggerAdapterFactory
        .getLogger(LogType.HZJT_LOGGER.val);

    @Autowired
    private IProjectService              projectService;
    @Autowired
    private IDirectoryService            directoryService;
    @Autowired
    private ICommonService               commonService;

    @RequestMapping(value = "/index")
    public String index(ModelMap model, HttpServletRequest request) {

        try {

            /*    String projectId = request.getParameter("projectId");*/
            request.setAttribute("msg", BaseController.getParameter("msg"));
            BaseController.removeParameter("msg");
            /*  model.addAttribute("projectId", projectId);*/

            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);

            if (userEmployee.getEmid() == null) {
                model.addAttribute("xmlevel", -1);
                model.addAttribute("mllevel", -1);
            } else {
                //项目等级
                Project data = new Project();
                data.setEmid(userEmployee.getEmid());
                List<Project> xmlevelList = projectService.getUserLevel(data);
                if (xmlevelList != null && !xmlevelList.isEmpty()) {
                    model.addAttribute("xmlevel", 0);
                } else {
                    model.addAttribute("xmlevel", -1);
                }

                //目录等级
                Directory directory = new Directory();
                directory.setEmid(userEmployee.getEmid());
                List<Directory> mllevelList = directoryService.getUserLevel(directory);
                if (mllevelList != null && !mllevelList.isEmpty()) {
                    model.addAttribute("mllevel", 1);
                } else {
                    model.addAttribute("mllevel", -1);
                }
            }

        } catch (Exception e) {
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }

        return "directory/directoryList";
    }

    @RequestMapping(value = "/List")
    @ResponseBody
    public ResponseResult List(ModelMap model, HttpServletRequest request,
                               @RequestParam(value = "rows", required = false) String pageSize,
                               @RequestParam(value = "page", required = false) String currentPage,
                               /* @RequestParam(value = "projectId", required = false) String projectId,*/
                               Directory data) {
        try {

            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            /* if (userEmployee.getUserid().equals("admin")) {
                Page page = new Page();
                page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
                page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
                BaseController.setSortByColumn(request, "directory_name", "asc");
                data.setOrderField((String) request.getAttribute("orderField"));
                data.setOrderFlag((String) request.getAttribute("orderFlag"));
                  data.setProjectId(
                projectId == null || projectId.equals("") ? null : Integer.valueOf(projectId));
                  data.setPrincipal(
                userEmployee.getEmid() == null ? null : String.valueOf(userEmployee.getEmid()));
                PaginationBean<Directory> paginationBean = directoryService.queryPageList(data,
                    page);
            
                ResponseResult result = new ResponseResult();
                result.setTotal(paginationBean.getTotalRecords());
                result.setRows(paginationBean.getPageList());
                return result;
            
            } else {*/
            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "directory_name", "asc");

            if (request.getAttribute("orderField").equals("projectName")) {
                data.setOrderField("p.project_name");
            } else if (request.getAttribute("orderField").equals("directoryName")) {
                data.setOrderField("d.directory_name");
            } else if (request.getAttribute("orderField").equals("addDate")) {
                data.setOrderField("d.add_date");
            } else if (request.getAttribute("orderField").equals("cz")) {
                data.setOrderField("p.project_name");
            } else {
                data.setOrderField((String) request.getAttribute("orderField"));
            }

            /*  data.setOrderField((String) request.getAttribute("orderField"));*/
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
            if (userEmployee.getEmid() != null) {
                data.setDirectoryPrincipal(String.valueOf(userEmployee.getEmid()));
                List<Directory> listdirectory_principal = directoryService
                    .selecdirectory_principal(data);

                if (listdirectory_principal != null && !listdirectory_principal.isEmpty()) {
                    String[] emids = new String[listdirectory_principal.size()];
                    int i = 0;
                    for (Directory directory : listdirectory_principal) {
                        emids[i] = directory.getDirectoryPrincipal();
                        i++;
                    }
                    data.setEmids(emids);
                }
            } else {
                data.setEmids(null);
            }
            data.setDirectoryAddPrincipal(
                userEmployee.getUid() == null ? null : String.valueOf(userEmployee.getUid()));
            /*   data.setAddUid(userEmployee.getUid() == null ? null : userEmployee.getUid());*/

            PaginationBean<Directory> paginationBean = directoryService.queryPageList(data, page);

            ResponseResult result = new ResponseResult();
            if (paginationBean.getPageList().isEmpty()) {
                result.setRows(new ArrayList<Directory>());
            } else {
                result.setRows(paginationBean.getPageList());
            }
            result.setTotal(paginationBean.getTotalRecords());
            return result;
            /*     }*/

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    /*  @RequestMapping(value = "List")
    public String index(ModelMap model, HttpServletRequest request,
                        @RequestParam(value = "pageSize", required = false) String pageSize,
                        @RequestParam(value = "currentPage", required = false) String currentPage,
                        @RequestParam(value = "projectId", required = false) String projectId,
                        Directory data) {
        User user = (User) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        try {
            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "directory_name", "asc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
            data.setProjectId(Integer.valueOf(projectId));
            PaginationBean<Directory> paginationBean = directoryService.queryPageList(data, page);
            model.addAttribute("list", paginationBean.getPageList());
            model.addAttribute("listPage", paginationBean);
            request.setAttribute("msg", BaseController.getParameter("msg"));
            BaseController.removeParameter("msg");
    
            model.addAttribute("currentPage",
                currentPage == null ? 0 : Integer.valueOf(currentPage));
            model.addAttribute("user", user);
            model.addAttribute("data", data);
            model.addAttribute("projectId", projectId);
            return "directory/directoryList";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return "error";
        }
    }*/

    @RequestMapping(value = "/addInInt", method = RequestMethod.GET)
    public String add(ModelMap model, HttpServletRequest request) {

        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            Employee employee = new Employee();
            /*  if (userEmployee.getEmid() != null) {
                Integer emid[] = { userEmployee.getEmid() };
                employee.setEmpids(emid);
            }*/
            java.util.List<Employee> List = commonService.queryNotCurrByAllEmployee(employee);
            model.addAttribute("List", List);

            Project data = new Project();
            data.setPrincipal(
                userEmployee.getEmid() == null ? null : String.valueOf(userEmployee.getEmid()));
            java.util.List<Project> projectList = projectService.queryList(data);

            model.addAttribute("projectList", projectList);
            return "directory/addDirectory";
        } catch (Exception e) {
            LOGGER.error("获得项目信息 queryList [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }

    }

    @RequestMapping(value = "/updateToview", method = RequestMethod.GET)
    public String updateToview(ModelMap model, HttpServletRequest request,
                               @RequestParam(value = "id") Integer id) {
        try {

            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            Employee employee = new Employee();
            /* if (userEmployee.getEmid() != null) {
                Integer emid[] = { userEmployee.getEmid() };
                employee.setEmpids(emid);
            }*/
            java.util.List<Employee> List = commonService.queryNotCurrByAllEmployee(employee);
            model.addAttribute("List", List);

            Project data = new Project();
            data.setPrincipal(
                userEmployee.getEmid() == null ? null : String.valueOf(userEmployee.getEmid()));
            java.util.List<Project> projectList = projectService.queryList(data);
            model.addAttribute("projectList", projectList);

            Directory data1 = new Directory();
            data1.setDirectoryId(id);
            data1 = directoryService.queryByPK(data1);
            model.addAttribute("data", data1);

            return "directory/updateDirectory";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public String details(ModelMap model, HttpServletRequest request,
                          @RequestParam(value = "id") Integer id) {
        try {

            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            Employee employee = new Employee();
            /*   if (userEmployee.getEmid() != null) {
                Integer emid[] = { userEmployee.getEmid() };
                employee.setEmpids(emid);
            }*/
            java.util.List<Employee> List = commonService.queryNotCurrByAllEmployee(employee);
            model.addAttribute("List", List);

            Project data = new Project();
            data.setPrincipal(
                userEmployee.getEmid() == null ? null : String.valueOf(userEmployee.getEmid()));
            java.util.List<Project> projectList = projectService.queryList(data);
            model.addAttribute("projectList", projectList);

            Directory data1 = new Directory();
            data1.setDirectoryId(id);
            data1 = directoryService.queryByPK(data1);
            model.addAttribute("data", data1);

            return "directory/detailsDirectory";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    /*   @SysLogger(description = "目录信息", moduleName = "目录管理", method = "新增")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(ModelMap model, HttpServletRequest request, Directory data) {
        try {
            directoryService.add(data);
            BaseController.setParameter("msg", "保存成功");
            return "redirect:List";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            e.printStackTrace();
            return "error";
        }
    }*/

    @SysLogger(description = "目录信息", moduleName = "目录管理", method = "删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(ModelMap model, HttpServletRequest request) {
        try {
            String[] idList = request.getParameter("idList").split(",");
            for (String id : idList) {
                Directory data = new Directory();
                data.setDirectoryId(Integer.valueOf(id));
                directoryService.delete(data);
            }
            BaseController.setParameter("msg", "删除成功");
            return "redirect:index";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    /*  @SysLogger(description = "目录信息", moduleName = "目录管理", method = "修改")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(ModelMap model, HttpServletRequest request, Directory data) {
        try {
            directoryService.update(data);
            BaseController.setParameter("msg", "保存成功");
            return "redirect:List";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return "error";
        }
    }
    */

    /**
     * 目录验证
     * 
     * @param request
     * @param directoryName
     * @param projectId
     * @param directoryId
     * @param directoryPrincipal
     * @return
     */
    @RequestMapping(value = "/validation")
    public @ResponseBody Map<String, Object> validation(HttpServletRequest request,
                                                        @RequestParam(value = "directoryName", required = false) String directoryName,
                                                        @RequestParam(value = "projectId", required = false) String projectId,
                                                        @RequestParam(value = "directoryId") String directoryId/*,
                                                                                                               @RequestParam(value = "directoryPrincipal") String directoryPrincipal*/) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            Directory data1 = new Directory();
            data1.setProjectId(Integer.valueOf(projectId));
            data1.setDirectoryId(directoryId.equals("null") || directoryId.equals("") ? null
                : Integer.valueOf(directoryId));
            data1.setDirectoryName(directoryName.trim());
            int count = directoryService.validation(data1);

            if (count == -99) {
                dataMap.put("msg", "-99");
                return dataMap;
            } else if (count == 0) {
                dataMap.put("msg", "0");
            } else {
                dataMap.put("msg", "-1");
                return dataMap;
            }
        } catch (Exception e) {
            LOGGER.error("调用services网络异常", e);
            dataMap.put("msg", "-99");
        }
        return dataMap;
    }

    @SysLogger(description = "目录信息", moduleName = "目录管理", method = "添加")
    @RequestMapping(value = "/add")
    public String add(ModelMap model, HttpServletRequest request, Directory data) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            data.setLevel(1);//等级
            data.setState(0); //状态
            data.setAddDate(new Date());
            data.setDirectoryAddPrincipal(String.valueOf(userEmployee.getUid()));
            directoryService.add(data);
            BaseController.setParameter("msg", "保存成功");
            return "redirect:index";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加目录信息 add [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "目录信息", moduleName = "目录管理", method = "新增")
    @RequestMapping(value = "/addSaveContinue", method = RequestMethod.POST)
    public String addSaveContinue(ModelMap model, HttpServletRequest request, Directory data) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            data.setLevel(1);//等级
            data.setState(0); //状态
            data.setAddDate(new Date());
            data.setDirectoryAddPrincipal(String.valueOf(userEmployee.getUid()));
            directoryService.add(data);
            return "redirect:addInInt";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加目录信息 add [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    /**
     * 新增目录
     * 
     * @param request
     * @return
     */
    /* @SysLogger(description = "目录信息", moduleName = "目录管理", method = "添加")
    @RequestMapping(value = "/add")
    public @ResponseBody Map<String, Object> add(HttpServletRequest request,
                                                 @RequestParam(value = "directoryName", required = false) String directoryName,
                                                 @RequestParam(value = "projectId", required = false) String projectId,
                                                 @RequestParam(value = "directoryId") String directoryId,
                                                 @RequestParam(value = "directoryPrincipal") String directoryPrincipal) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
    
        try {
            Directory data1 = new Directory();
            data1.setProjectId(Integer.valueOf(projectId));
            data1.setDirectoryId(directoryId.equals("null") || directoryId.equals("") ? null
                : Integer.valueOf(directoryId));
            data1.setDirectoryName(directoryName.trim());
            int count = directoryService.validation(data1);
    
            if (count == -99) {
                dataMap.put("msg", "-99");
                return dataMap;
            } else if (count == 0) {
    
            } else {
                dataMap.put("msg", "-1");
                return dataMap;
            }
               Project project = new Project();
            project.setId(projectId.equals("null") || projectId.equals("") ? null
                : Integer.valueOf(projectId));
            project = projectService.queryByPK(project);
    
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
    
            Directory data = new Directory();
            data.setDirectoryName(directoryName);//目录名称
            data.setLevel(1);//等级
            data.setDirectoryPrincipal(directoryPrincipal); //负责人
            data.setState(0); //状态
            data.setProjectId(Integer.valueOf(projectId));//项目id
            data.setAddDate(new Date());
            data.setDirectoryAddPrincipal(String.valueOf(userEmployee.getUid()));
    
            directoryService.add(data);
            dataMap.put("msg", "100");
            BaseController.setParameter("msg", "保存成功");
            return dataMap;
        } catch (Exception e) {
            LOGGER.error("调用services网络异常", e);
            dataMap.put("msg", "-99");
            return dataMap;
        }
    
    }*/

    /**
     * 修改目录
     * 
     * @param request
     * @return
     */

    @SysLogger(description = "目录信息", moduleName = "目录管理", method = "修改")
    @RequestMapping(value = "/update")
    public String update(ModelMap model, HttpServletRequest request, Directory data) {
        try {
            data.setLevel(1);//等级
            data.setState(0); //状态
            directoryService.update(data);
            BaseController.setParameter("msg", "保存成功");
            return "redirect:index";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("修改目录信息 update [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    /* @SysLogger(description = "目录信息", moduleName = "目录管理", method = "修改")
    @RequestMapping(value = "/update")
    public @ResponseBody Map<String, Object> update(HttpServletRequest request,
                                                    @RequestParam(value = "directoryName", required = false) String directoryName,
                                                    @RequestParam(value = "projectId", required = false) String projectId,
                                                    @RequestParam(value = "directoryId") String directoryId,
                                                    @RequestParam(value = "directoryPrincipal") String directoryPrincipal) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
    
        try {
            Directory data1 = new Directory();
            data1.setProjectId(Integer.valueOf(projectId));
            data1.setDirectoryId(directoryId.equals("null") || directoryId.equals("") ? null
                : Integer.valueOf(directoryId));
            data1.setDirectoryName(directoryName.trim());
            int count = directoryService.validation(data1);
    
            if (count == -99) {
                dataMap.put("msg", "-99");
                return dataMap;
            } else if (count == 0) {
    
            } else {
                dataMap.put("msg", "-1");
                return dataMap;
            }
    
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
    
            Directory data = new Directory();
            data.setDirectoryName(directoryName);//目录名称
            data.setLevel(1);//等级
            data.setDirectoryPrincipal(directoryPrincipal); //负责人
            data.setState(0); //状态
            data.setProjectId(Integer.valueOf(projectId));//项目id
            data.setDirectoryId(Integer.valueOf(directoryId));//目录id
            data.setDirectoryAddPrincipal(String.valueOf(userEmployee.getUid()));//添加人
            directoryService.update(data);
            dataMap.put("msg", "100");
            BaseController.setParameter("msg", "保存成功");
            return dataMap;
        } catch (Exception e) {
            LOGGER.error("调用services网络异常", e);
            dataMap.put("msg", "-99");
            return dataMap;
        }
    
    }*/
    /**
     * 查询项目目录
     * 
     * @param model
     * @param request
     * @param id
     * @return
     */
    /*  @RequestMapping(value = "/updateToview", method = RequestMethod.GET)
    public String updateToview(ModelMap model, HttpServletRequest request,
                               @RequestParam(value = "id") Integer id) {
        try {
            Project data = new Project();
            data.setId(id);
            data = projectService.queryByPK(data);
            model.addAttribute("data", data);
    
            return "project/updateProject";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return "error";
        }
    }*/

    /**
     * 添加项目过滤项目添加人
     * 
     * @param request
     * @param directoryName
     * @param projectId
     * @param directoryId
     * @param directoryPrincipal
     * @return
     */
    @RequestMapping(value = "/selectProject")
    public @ResponseBody Map<String, Object> selectProject(HttpServletRequest request,
                                                           @RequestParam(value = "projectId", required = false) Integer projectId) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        UserEmployee userEmployee = (UserEmployee) request.getSession()
            .getAttribute(Constant.LOGIN_CONSOLE_USER);
        try {
            Project data1 = new Project();
            data1.setId(projectId);

            if (userEmployee.getEmid() != null) {
                Integer emid[] = { userEmployee.getEmid() };
                data1.setEmpids(emid);
            }
            List<Project> list = projectService.selectProjectByid(data1);
            if (list != null && !list.isEmpty()) {
                dataMap.put("list", list);
                dataMap.put("msg", "100");
            } else {
                dataMap.put("msg", "-100");
                return dataMap;
            }
        } catch (Exception e) {
            LOGGER.error("调用services网络异常", e);
            dataMap.put("msg", "-99");
        }
        return dataMap;
    }
}
